package com.itheima.kafka.simple;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.protocol.types.Field;

import java.util.Properties;

/**
 * 消息生产者
 */
public class ProducerFastStart {

    private static final String INPUT_TOPIC="input_topic";

    public static void main(String[] args) {

        //添加kafka的配置信息
        Properties properties = new Properties();
        //配置broker信息
        properties.put("bootstrap.servers","192.168.14.37:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.RETRIES_CONFIG,10);

        //生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        //封装消息
        for (int i = 0; i < 10; i++) {
            if(i % 2 == 0){
                ProducerRecord<String,String> record = new ProducerRecord<String, String>(INPUT_TOPIC,"00001"+i,"hello kafka");
                producer.send(record);
            }else {
                ProducerRecord<String,String> record = new ProducerRecord<String, String>(INPUT_TOPIC,"00002"+i,"hello stream");
                producer.send(record);
            }
        }

        //发送消息
        /*try {
            *//*RecordMetadata recordMetadata = producer.send(record).get();
            System.out.println(recordMetadata.offset());*//*
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if(e!=null){
                        e.printStackTrace();
                    }
                    System.out.println(recordMetadata.offset());
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }*/

        //关系消息通道
        producer.close();
    }
}
